# coding=utf-8
from ToolsConfig import serverCompFactory, clientCompFactory, serverApi, LevelId
from ItemTools import IsSameItem


def DictFromBlockEntityData(blockEntityData, posDim):
    """
    从方块实体中获取全部数据
    :param blockEntityData:方块实体自定义数据
    :param posDim:坐标维度
    :return:dict
    """
    data = getattr(getattr(blockEntityData, '_BlockEntityData__exDataMgr'), 'mBlockEntityData')
    return data[posDim[3]][posDim[:3]]


def SetBlockAir(posDim):
    """
    设置某位置的方块为空，仅服务端可用
    """
    return serverCompFactory.CreateBlockInfo(LevelId).SetBlockNew(
        posDim[:3], {'name': 'minecraft:air'}, dimensionId=posDim[3]
    )


def GetEntityDim(entityId):
    """
    获取实体维度，仅服务端可用
    """
    return serverCompFactory.CreateDimension(entityId).GetEntityDimensionId()


def DeclarePlayerInvItem(playerId, itemDict1, count=1):
    """
    减少玩家背包内特定物品
    :param playerId:玩家ID
    :param count:减少数量
    :param itemDict1:需要检测的物品字典,必须包含newItemName字段
    :return:是否成功减少
    """
    itemComp = serverCompFactory.CreateItem(playerId)
    itemDicts = itemComp.GetPlayerAllItems(0)
    for index in range(itemDicts.__len__()):
        itemDict = itemDicts[index]
        if itemDict and IsSameItem(itemDict, itemDict1):
            itemComp.SetInvItemNum(index, itemDict['count'] - count)
            return True
    return False


def GetEntityCarriedItem(entityId):
    """
    获取玩家右手物品
    """
    return serverCompFactory.CreateItem(entityId).GetEntityItem(2, 0, True)


def GetEntityTypeComp(entityId):
    """
    获取实体类型组件
    """
    return serverCompFactory.CreateEngineType(entityId) or clientCompFactory.CreateEngineType(entityId)


def IsPlayer(entityId):
    """
    判断一个实体是否为玩家
    """
    player = serverApi.GetMinecraftEnum().EntityType.Player
    return GetEntityTypeComp(entityId).GetEngineType() & player == player


def GetEntityItemComp(entityId):
    """
    获取实体类型组件
    """
    return serverCompFactory.CreateItem(entityId) or clientCompFactory.CreateItem(entityId)


def DeclarePlayerCarriedItem(playerId):
    """
    减少玩家右手物品一个，仅服务端有效
    """
    itemComp = GetEntityItemComp(playerId)
    itemDict = itemComp.GetPlayerItem(2, 0, True)
    if itemDict:
        itemDict['count'] -= 1
        return itemComp.SpawnItemToPlayerCarried(itemDict, playerId)
